﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Input;
using DiscoveryLogic.UI.Layouts.Converters;
using DiscoveryLogic.UI.Layouts.DataAccesses;
using DiscoveryLogic.DataServices.DataSources;
using System.ComponentModel;

namespace DiscoveryLogic.UI.Layouts.ContentScreens
{
    [ScriptableType]
    public partial class BillPay : UserControl, IContentScreen
    {
        #region Private Variables

        // private List<BillPayeeForDataBinding> listOfPayees;
        double accountFunds;
       //  private SliderDateForDataBinding sliderSelectedDate;

        private const string CONTROL_TEXTBOX_PAYEE = "txtPayee";
        private const string CONTROL_MINIBILLGRID_HISTORY = "mbgHistory";
        private const string CONTROL_CHECKBOX_RECURRING = "chRecurring";
        private const string CONTROL_BUTTON_LASTAMOUNT = "btnLastAmount";
        private const string CONTROL_TEXTBOX_AMOUNT = "txtAmount";
        private const string CONTROL_TEXTBOX_WITHDRAWLDATE = "txtWithdrawlDate";

        private const double CALENDAR_WIDTH = 195;

        #endregion

        #region Constructors
        BillPayModel _model
        {
            get
            {
                BillPayModelDesignTime designtime = this.Resources["DesignTimeData"] as BillPayModelDesignTime;
                
                if ( designtime != null )  
                    return designtime.Data ;
                return null; 
            } 
        } 

        public BillPay()
        {
            InitializeComponent();

            this.Loaded +=new RoutedEventHandler(OnLoaded);
 
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// An amount is changed - recalculate the payments due
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtAmount_TextChanged(object sender, RoutedEventArgs e)
        {
            _model.SliderDate.RecalculateAmounts();
        }

        // Mouse Events for Menu links

        protected void MenuLink_MouseEnter(object sender, EventArgs e)
        {
            ((UIElement)sender).Opacity = 1;
            ((FrameworkElement)sender).Cursor = Cursors.Hand;
        }

        protected void MenuLink_MouseLeave(object sender, EventArgs e)
        {
            ((UIElement)sender).Opacity = 0.7;
            ((FrameworkElement)sender).Cursor = Cursors.Arrow;
        }

        protected void MouseEnter_Hand(object sender, EventArgs e)
        {
            //FrameworkElement btn = sender as FrameworkElement;
            //BillPayeeForDataBinding billPayee = btn.DataContext as BillPayeeForDataBinding;
            //if (billPayee != null && !billPayee.IsRecurring)
            //{
                ((FrameworkElement)sender).Cursor = Cursors.Hand;
            //}
        }

        protected void MouseLeave_Arrow(object sender, EventArgs e)
        {
            //FrameworkElement btn = sender as FrameworkElement;
            //BillPayeeForDataBinding billPayee = btn.DataContext as BillPayeeForDataBinding;
            //if (billPayee != null && !billPayee.IsRecurring)
            //{
                ((FrameworkElement)sender).Cursor = Cursors.Arrow;
            //}
        }

        /// <summary>
        /// Submit button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Submit_Click(object sender, EventArgs e)
        {
            if (GoHome != null)
            {
                GoHome(this, new EventArgs());
            }
        }

        /// <summary>
        /// When a mini history graph is clicked, open popup and set context
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void MiniGraph_Click(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement miniBillGraph = sender as FrameworkElement;
            BillPaymentHistory billPaymentHistory = miniBillGraph.DataContext as BillPaymentHistory;
            BillGraphPopup.SetGraph(billPaymentHistory.BillHistory, billPaymentHistory.PayeeName);
            BillGraphPopup.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// Handles event where "X" is clicked on the popup history graph window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPopupClose_Clicked(object sender, MouseButtonEventArgs e)
        {
            BillGraphPopup.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Handles when the Last Amount button is clicked - gets the last amount and 
        /// populates the Amount textbox
        /// </summary>
        private void LastAmountButton_Click(object sender, RoutedEventArgs e)
        {
            FrameworkElement btnClick = sender as FrameworkElement;
            if (btnClick != null)
            {
                BillPayeeForDataBinding billPayeeClicked = btnClick.DataContext as BillPayeeForDataBinding;
                if (billPayeeClicked != null)
                {
                    //the following raises an event that tells the UI to update accordingly
                    billPayeeClicked.Amount = billPayeeClicked.BillPaymentHistory.GetLastPaymentAmount();
                }
            }

            //the following raises an event that tells the UI to update accordingly
            _model.SliderDate.RecalculateAmounts();
        }

        /// <summary>
        /// On Calendar icon click, open calendar control popup
        /// </summary>
        private void CalendarImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement calendarImage = sender as FrameworkElement;
            BillPayeeForDataBinding billPayee = calendarImage.DataContext as BillPayeeForDataBinding;
            if (!billPayee.IsRecurring)
            {
                double left = e.GetPosition(MainContent).X - CALENDAR_WIDTH;
                double top = e.GetPosition(MainContent).Y + 10;

                CalendarPopup.SetValue(Canvas.LeftProperty, left);
                CalendarPopup.SetValue(Canvas.TopProperty, top);

                CalendarPopup.DataContext = calendarImage.DataContext;
                CalendarPopup.SelectedDate = billPayee.WithdrawlDate;
                CalendarPopup.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// On date selected in calendar control, update selected date and recalculate amounts
        /// </summary>
        private void Calendar_DateSelected(object sender, SelectionChangedEventArgs e)
        {
            System.Windows.Controls.Calendar currCalendar = sender as System.Windows.Controls.Calendar;
            if (currCalendar != null)
            {
                BillPayeeForDataBinding billPayee = currCalendar.DataContext as BillPayeeForDataBinding;
                DateTime selectedDate = CalendarPopup.SelectedDate.Value;
                billPayee.WithdrawlDate = selectedDate;

                // Turn off calendar control
                CalendarPopup.Visibility = Visibility.Collapsed;

                // Update totals
                _model.SliderDate.RecalculateAmounts();
            }
        }

        // This method is called when the the canvas has loaded
        // Used to initialize variables and set screen elements
        private void OnLoaded(object sender, EventArgs e)
        {
            try
            {
                // Connect to web service and get list of BillPayees
                // _model = this.Resources["DesignTimeData"] as BillPayModel; 

                //Set the bindings for the controls
                // InitializeBindings();
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }

            
        }

        

        #endregion
        
        #region Helper Methods

        public void ScreenHideActions()
        {
            CalendarPopup.Visibility = Visibility.Collapsed;
        }

        public void ScreenShowActions()
        {
        }

      

        /// <summary>
        /// Set up the bindings for the controls
        /// </summary>
        //private void InitializeBindings()
        //{
        //    //Set up bindings
        //    sliderSelectedDate = new SliderDateForDataBinding(listOfPayees, accountFunds);
        //    icBillPay.ItemsSource = listOfPayees;
        //    AccountFunds.Text = accountFunds.ToCurrency();
        //    TotalAmount.DataContext = sliderSelectedDate;
        //    FundsAfter.DataContext = sliderSelectedDate;
        //    sliderBarViewDate.DataContext = sliderSelectedDate;
        //    txtAsOfDate.DataContext = sliderSelectedDate;            
        //}
             
        #endregion

        #region Events

        public event EventHandler GoHome;

        #endregion
    }

    public class BillPayModelDesignTime 
    {
        public BillPayModelDesignTime()
        {
        }

        public BillPayModel InstanceData
        {
            get
            {
                if (_singleton == null)
                    _singleton = Data; 
                return _singleton;
            } 
        } 

        protected static BillPayModel _singleton; 
        public  BillPayModel Data   
        {
            get
            { 
                if ( _singleton == null ) 
                {
                        BillPaymentManager BillPayManager = new BillPaymentManager();                 
                         AccountManager AccManager = new AccountManager();
                         List<Account> checkingAccounts = AccManager.GetAccounts(AccountType.Checking);


                         double accountFunds = 0; 
                         if (checkingAccounts != null && checkingAccounts.Count > 0)
                         {
                             // Set account funds
                             accountFunds = checkingAccounts[0].Balance;
                         } 
                            
                         // listOfPayees = BillPayManager.GetPayees();

                          _singleton = new BillPayModel(BillPayManager.GetPayees(), accountFunds);
                }
                return _singleton; 
            } 
        } 

    } 

    public class BillPayModel  : INotifyPropertyChanged 
    {        

        public BillPayModel  ( List<BillPayeeForDataBinding> payees, double funds ) 
        {
            System.Diagnostics.Debug.WriteLine("BillPayModel with " + payees.Count + " and " + funds.ToCurrency()); 
            _payees = payees; 
            _funds = funds; 
        } 

        List<BillPayeeForDataBinding> _payees ;
        protected double _funds;

        protected SliderDateForDataBinding _sliderDate; 
        public SliderDateForDataBinding SliderDate
        {
            get
            {
                if (_sliderDate == null)
                {
                    _sliderDate = new SliderDateForDataBinding(Payees, Funds);
                }
                return _sliderDate; 
            } 
        }

        public List<BillPayeeForDataBinding> Payees
        {

            get
            {
                return _payees;
            }
        }

        public double Funds
        {
            get
            {
                return _funds;
            }
        }

        public string FundsCurrency
        {
            get
            {
                return _funds.ToCurrency();
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
    } 
}

